import * as types from '../constants/loginTypes'
import * as WeChat from 'react-native-wechat'
import { DeviceEventEmitter, Platform } from 'react-native'
import { Actions } from 'react-native-router-flux'
import API from '../../api/request'

// 登录
export function login(parentId = 0) {
	return async dispatch => {
		dispatch(isLogining(parentId))
		getCode(parentId, dispatch)

// 		await global.storage.save({
// 			key: types.LOGIN_TOKEN,
// 			data:
// 				'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI2IiwiZXhwIjo2NDA2MzIzODQwMH0.SfFA29j6FjBHWTw4TdSOnxm-J2P2DV_31IjvZODc-QI'
// 		})
// 		DeviceEventEmitter.emit('login.success')
// 		getUserInfoApi(dispatch)
// 		getServiceInfoApi(dispatch)
// 		getHomeDataApi(dispatch)
//      getWXName(dispatch)
// 		Actions.pop()
    }
}

export function getHomeData() {
	return dispatch => {
		getHomeDataApi(dispatch)
	}
}

// 退出
export function logout() {
	return async dispatch => {
		const url = '/api/user/logout'
		let isLogout = false
		let res = await API.post(url)
		if (global.isApiFetchingSuccess(res)) {
			global.storage.remove({
				key: types.LOGIN_TOKEN
			})
			isLogout = res.data
			isLogout && dispatch(isUpdateLogout(isLogout))
			isLogout && dispatch(clear())
			// Actions.login()
		}
	}
}

// 获取公司微信公众号
async function getWXName (dispatch) {
		let url = '/api/skip/gainWechatOfficialAccount'
			let res = await API.get(url)
			if (global.isApiFetchingSuccess(res)) {
				let info = res.data || {}
				dispatch(updateWXInfo(info))
			}
}

// 获取最新版本 TODO
// async function getAppVersionApi () {
// 	let url = '/api/system/curVersion/'+Platform.OS
// 	let res = await API.post(url)
// 	if (global.isApiFetchingSuccess(res)) {
// 		let info = res.data || {}
// 		// dispatch(isUpdateUserInfo(user))
// 	}
// }

export function userInfo() {
	return async dispatch => {
		getUserInfoApi(dispatch)
	}
}

export function clearUserinfo() {
	return dispatch => {
		dispatch(clear())
	}
}

// 微信登录之 授权
function getCode(parentId, dispatch) {
	let scope = 'snsapi_userinfo'
	let state = 'wechat_sdk_' + new Date().getTime()
	WeChat.isWXAppInstalled().then(isInstalled => {
		if (isInstalled) {
			// 获取微信授权
			WeChat.sendAuthRequest(scope, state)
				.then(responseCode => {
					loginWX(
						{
							wxCode: responseCode.code,
							parentId
						},
						dispatch
					)
				})
				.catch(error => {
					dispatch(loginError('登录授权发生错误：' + error.message))
				})
		} else {
			dispatch(loginError('没有安装微信'))
		}
	})
}

// 获取用户信息api
async function getUserInfoApi(dispatch) {
	const url = '/api/user/userInfo'
	let res = await API.post(url)
	if (global.isApiFetchingSuccess(res)) {
		let user = res.data || {}
		dispatch(isUpdateUserInfo(user))
	}
}

// 获取客服信息数据
async function getServiceInfoApi(dispatch) {
	let url = '/api/system/service_info'
	let res = await API.get(url)
	if (global.isApiFetchingSuccess(res)) {
		dispatch(isUpdateServiceInfo(res.data))
	} else {
		// dispatch(_apiServiceGetError(res.message))
	}
}

// 获取首页数据
async function getHomeDataApi(dispatch) {
	let url = '/api/user/home'
	let res = await API.post(url)
	if (global.isApiFetchingSuccess(res)) {
		dispatch(isUpdateHomeData(res.data && res.data.countInfo))
	} else {
		// dispatch(_apiHomeGetError(res.message))
	}
}

// 登录
async function loginWX(info, dispatch) {
	const url = '/api/user/wxlogin'
	let res = await API.post(url, info)
	if (global.isApiFetchingSuccess(res)) {
		let token = res.data
		if (token) {
			dispatch(isUpdateToken(token))
			await global.storage.save({
				key: types.LOGIN_TOKEN,
				data: token
			})
			DeviceEventEmitter.emit('login.success')
			getUserInfoApi(dispatch)
			getServiceInfoApi(dispatch)
			getHomeDataApi(dispatch)
			getWXName(dispatch)
			Actions.pop()
			// let list = Actions.state.routes || []
			// let popNum = 1
			// list.forEach((item, index) => {
			//   let routes = item.routes
			//   let isLogin = routes.find(i => i.key === 'login')
			//   if (isLogin) popNum++
			// })
			// Actions.pop({
			//   popNum
			// })
		}
	} else {
		dispatch(loginError(res))
	}
}

function isLogining() {
	return {
		type: types.LOGIN_IN_DOING
	}
}

function loginError(err) {
	return {
		type: types.LOGIN_IN_ERROR,
		err
	}
}

function clear() {
	return {
		type: types.LOGIN_CLEAR
	}
}

function isUpdateUserInfo(user) {
	return {
		type: types.UPDATE_USERINFO,
		user
	}
}

function isUpdateToken(token) {
	return {
		type: types.UPDATE_TOKEN,
		token
	}
}

function isUpdateServiceInfo(info) {
	return {
		type: types.UPDATE_SERVICEINFO,
		info
	}
}

function isUpdateHomeData(info) {
	return {
		type: types.UPDATE_HOMEDATA,
		info
	}
}

function isUpdateLogout(isLogout) {
	return {
		type: types.UPDATE_LOGOUT,
		isLogout
	}
}

function updateWXInfo (info) {
	return {
		type: types.UPDATE_WXINFO,
		info
	}
}
